'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { adminApi } from '@/lib/api-client'
import {
  ExternalLink,
  Edit,
  Trash2,
  Eye,
  EyeOff,
  RefreshCw,
  Globe
} from 'lucide-react'

interface Tool {
  id: string
  title: string
  description: string
  url: string
  deployPath?: string
  isDeployed: boolean
  status: 'PENDING' | 'APPROVED' | 'REJECTED'
  category: {
    name: string
    icon: string
  }
  user: {
    name: string
  }
  createdAt: string
  originalFile?: string
  // 判断是否为外部工具
  isExternal?: boolean
}

export function ToolManagement() {
  const [tools, setTools] = useState<Tool[]>([])
  const [loading, setLoading] = useState(true)
  const [filter, setFilter] = useState<'all' | 'external' | 'deployed' | 'pending'>('all')

  useEffect(() => {
    fetchTools()
  }, [])

  const fetchTools = async () => {
    try {
      setLoading(true)
      const result = await adminApi.getTools()

      if (result.success) {
        // 标识外部工具
        const toolsWithType = (result.data || []).map((tool: Tool) => ({
          ...tool,
          isExternal: !tool.deployPath || tool.deployPath.trim() === ''
        }))
        setTools(toolsWithType)
      } else {
        console.error('获取工具列表失败:', result.error)
      }
    } catch (error) {
      console.error('获取工具列表失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleToggleStatus = async (toolId: string, currentStatus: boolean) => {
    try {
      const result = await adminApi.toggleTool(toolId, !currentStatus)

      if (result.success) {
        await fetchTools()
      } else {
        console.error('切换工具状态失败:', result.error)
      }
    } catch (error) {
      console.error('切换工具状态失败:', error)
    }
  }

  const handleDeleteTool = async (toolId: string) => {
    if (!confirm('确定要删除这个工具吗？此操作不可恢复。')) {
      return
    }

    try {
      const result = await adminApi.deleteTool(toolId)

      if (result.success) {
        await fetchTools()
      } else {
        console.error('删除工具失败:', result.error)
      }
    } catch (error) {
      console.error('删除工具失败:', error)
    }
  }

  const handleRedeployTool = async (toolId: string) => {
    try {
      const result = await adminApi.redeployTool(toolId)

      if (result.success) {
        await fetchTools()
      } else {
        console.error('重新部署失败:', result.error)
      }
    } catch (error) {
      console.error('重新部署失败:', error)
    }
  }

  const handleEditTool = (toolId: string) => {
    // 跳转到工具编辑页面
    window.location.href = `/admin/tools/${toolId}/edit`
  }

  const filteredTools = tools.filter(tool => {
    switch (filter) {
      case 'external':
        return tool.isExternal
      case 'deployed':
        return !tool.isExternal && tool.isDeployed
      case 'pending':
        return !tool.isExternal && !tool.isDeployed
      default:
        return true
    }
  })

  if (loading) {
    return (
      <div className="space-y-4">
        {Array.from({ length: 3 }).map((_, i) => (
          <Card key={i} className="animate-pulse">
            <CardContent className="p-6">
              <div className="h-4 bg-gray-200 rounded w-1/4 mb-2"></div>
              <div className="h-3 bg-gray-200 rounded w-3/4 mb-4"></div>
              <div className="flex gap-2">
                <div className="h-8 bg-gray-200 rounded w-20"></div>
                <div className="h-8 bg-gray-200 rounded w-20"></div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 过滤器 */}
      <div className="flex flex-wrap gap-4">
        <Button
          variant={filter === 'all' ? 'default' : 'outline'}
          onClick={() => setFilter('all')}
        >
          全部工具 ({tools.length})
        </Button>
        <Button
          variant={filter === 'external' ? 'default' : 'outline'}
          onClick={() => setFilter('external')}
        >
          <Globe className="h-4 w-4 mr-2" />
          外部工具 ({tools.filter(t => t.isExternal).length})
        </Button>
        <Button
          variant={filter === 'deployed' ? 'default' : 'outline'}
          onClick={() => setFilter('deployed')}
        >
          已部署 ({tools.filter(t => !t.isExternal && t.isDeployed).length})
        </Button>
        <Button
          variant={filter === 'pending' ? 'default' : 'outline'}
          onClick={() => setFilter('pending')}
        >
          未部署 ({tools.filter(t => !t.isExternal && !t.isDeployed).length})
        </Button>
        <Button variant="outline" onClick={fetchTools}>
          <RefreshCw className="h-4 w-4 mr-2" />
          刷新
        </Button>
      </div>

      {/* 工具列表 */}
      <div className="space-y-4">
        {filteredTools.length === 0 ? (
          <Card>
            <CardContent className="p-6 text-center">
              <p className="text-gray-500">暂无工具</p>
            </CardContent>
          </Card>
        ) : (
          filteredTools.map((tool) => (
            <Card key={tool.id}>
              <CardHeader>
                <div className="flex items-start justify-between">
                  <div>
                    <CardTitle className="flex items-center gap-2">
                      {tool.title}
                      {tool.isExternal ? (
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                          <Globe className="h-3 w-3 mr-1" />
                          外部工具
                        </span>
                      ) : (
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          tool.isDeployed
                            ? 'bg-green-100 text-green-800'
                            : 'bg-yellow-100 text-yellow-800'
                        }`}>
                          {tool.isDeployed ? '已部署' : '未部署'}
                        </span>
                      )}
                    </CardTitle>
                    <CardDescription className="mt-1">
                      {tool.description}
                    </CardDescription>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                      {tool.category.icon} {tool.category.name}
                    </span>
                  </div>
                </div>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {/* 工具信息 */}
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="font-medium">发布者:</span> {tool.user.name}
                    </div>
                    <div>
                      <span className="font-medium">创建时间:</span> {new Date(tool.createdAt).toLocaleDateString()}
                    </div>
                    {tool.deployPath && (
                      <div>
                        <span className="font-medium">部署路径:</span> {tool.deployPath}
                      </div>
                    )}
                    {tool.originalFile && (
                      <div>
                        <span className="font-medium">原始文件:</span> {tool.originalFile}
                      </div>
                    )}
                  </div>

                  {/* 操作按钮 */}
                  <div className="flex flex-wrap gap-2">
                    {tool.isExternal ? (
                      // 外部工具操作
                      <>
                        <Button
                          size="sm"
                          onClick={() => window.open(tool.url, '_blank')}
                        >
                          <ExternalLink className="h-4 w-4 mr-2" />
                          访问外部工具
                        </Button>

                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleToggleStatus(tool.id, tool.isDeployed)}
                        >
                          {tool.isDeployed ? (
                            <>
                              <EyeOff className="h-4 w-4 mr-2" />
                              下线
                            </>
                          ) : (
                            <>
                              <Eye className="h-4 w-4 mr-2" />
                              上线
                            </>
                          )}
                        </Button>
                      </>
                    ) : (
                      // 本地部署工具操作
                      <>
                        {tool.isDeployed && tool.deployPath && (
                          <div className="flex gap-2">
                            <Button
                              size="sm"
                              onClick={() => window.open(`${tool.url}?pure=true`, '_blank')}
                            >
                              <ExternalLink className="h-4 w-4 mr-2" />
                              访问工具
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => window.open(`${tool.url}?minimal=true`, '_blank')}
                            >
                              极简模式
                            </Button>
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => window.open(tool.url, '_blank')}
                            >
                              完整页面
                            </Button>
                          </div>
                        )}

                        <Button
                          size="sm"
                          variant="outline"
                          onClick={() => handleToggleStatus(tool.id, tool.isDeployed)}
                        >
                          {tool.isDeployed ? (
                            <>
                              <EyeOff className="h-4 w-4 mr-2" />
                              下线
                            </>
                          ) : (
                            <>
                              <Eye className="h-4 w-4 mr-2" />
                              部署
                            </>
                          )}
                        </Button>

                        {tool.isDeployed && (
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleRedeployTool(tool.id)}
                          >
                            <RefreshCw className="h-4 w-4 mr-2" />
                            重新部署
                          </Button>
                        )}
                      </>
                    )}

                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleEditTool(tool.id)}
                    >
                      <Edit className="h-4 w-4 mr-2" />
                      编辑
                    </Button>

                    <Button
                      size="sm"
                      variant="outline"
                      onClick={() => handleDeleteTool(tool.id)}
                      className="text-red-600 hover:text-red-700"
                    >
                      <Trash2 className="h-4 w-4 mr-2" />
                      删除
                    </Button>
                  </div>
                </div>
              </CardContent>
            </Card>
          ))
        )}
      </div>
    </div>
  )
}
